"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 登陆接口
 */
class LoginController extends Controller {
  /**
   * @summary 登陆验证
   * @router post /api/login
   * @request body LoginBody 用户名密码
   */
  async login() {
    const { ctx, app } = this;
    // 1.验证用户
    const user = ctx.request.body;
    const res = await ctx.model.User.findOne({
      where: user,
    });
    if (res == null) {
      ctx.body = {
        code: 400,
        msg: "用户名或密码错误",
      };
      return;
    }
    // 2.下发token
    const token = await app.jwt.sign(user, app.config.jwt.secret, {
      expiresIn: 60 * 60,
    });
    ctx.body = {
      code: 200,
      msg: "登陆成功",
      data: token,
    };
  }

  /**
   * @summary 校验token
   * @router get /api/checkToken
   * @apikey
   */
  async checkToken() {
    const { ctx, app } = this;
    const token = ctx.request.headers.authorization;
    let decode = null;
    try {
      decode = app.jwt.verify(token, app.config.jwt.secret);
    } catch (error) {
      if (error.name === "JsonWebTokenError") {
        ctx.response.status = 401;
        ctx.body = { code: 401, msg: "token无效" };
        return;
      }
    }
    ctx.body = {
      code: 200,
      msg: "token校验通过",
      data: decode,
    };
  }
}

module.exports = LoginController;
